<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\api\model\ActivityMessageModel;
use app\api\model\ActType;
use app\api\model\UserModel;
use app\api\service\Url;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Db;
use think\Request;

class CommunityActivityController
{
    /**
     * 社区消息推送功能
     */
    public function sendMessage(Request $request){
        $appid = config('wxchat.appid');
        $appsecret =config('wxchat.appsecret');
        $touser = $request->param('touser');
        $template_id = config('wxchat.template_id');
        //获取access_token
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;

        $res = json_decode(file_get_contents($url),true);

        $access_token = $res['access_token'] ;

        //请求url
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $access_token ;

        //发送内容
        $data = [] ;

        //接收者（用户）的 openid
        var_dump($touser);

        $messages=ActivityMessageModel::where('user_id',$touser)->find();
        $user_obj=UserModel::where('id',$touser)->find();
        $openid=$user_obj['openid'];

        $data['touser'] = $openid;

        //所需下发的订阅模板id
        $data['template_id'] = $template_id ;

        //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
        $data['page'] = 'index' ;

        //模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
        $data['data'] = [
            "thing1"=>[
                "value"=>$messages['activity_name']
            ],
            "date2"=>[
                "value"=>date('Y-m-d H:i:s')
            ],
            "character_string3"=>[
                "value"=>$messages['order_id']
            ],
            "thing4"=> [
                "value"=> $messages['activity_type']
            ],
            "thing9"=>[
                "value"=> $messages['desc']
            ]
        ];

        //跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
        $data['miniprogram_state'] = 'formal' ;

        $obj= Url::posturl($url,$data) ;
        return json_encode(['code' => 200, 'msg' => '成功','uid'=>$obj]);

    }

    /**
     * @param Request $request
     * @return false|string
     * 登录（未完）
     */
    public function login(Request $request)
    {
        $appid = $request->param('appid');
        $appsecret = $request->param('appsecret');
        $code=$request->param('code');
        //获取openid
        $urls = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=authorization_code";
        $result =Url::geturl($urls);
        $model =UserModel::getUserInfo($result['openid']);
        if (empty($model)){
            $data=[];
            $data['session_key']=$result['session_key'];
            $data['openid']=$result['openid'];
            $res=UserModel::create($data);
        }
        /**
         * 获取信息（...）
         */
        if ($res){
            return json_encode(['code' => 200, 'msg' => '成功','data'=>true]);
        }else{
            return json_encode(['code' => 500, 'msg' => '成功','data'=>$res]);
        }

    }

    /**
     * 活动类型
     */
    public static function type(){
        $data=ActType::select();
        $arr['code']=0;
        $arr['msg']='成功';
        $arr['count']=count($data);
        $arr['data']=$data;
        return json($arr);
    }
    /**
     * 活动添加
     */
    public static function addMessage(Request $request){
        $data=$request->post();
        return $data;
    }
}
